package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.customer.enums.CertificationAuditStatusEnum;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.AgencyCertificationAuditResDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationAuditResDTO;
import com.jzo2o.customer.service.IAgencyCertificationAuditService;
import com.jzo2o.customer.service.IAgencyCertificationService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * <p>
 * 机构认证信息审核表 服务实现类
 * </p>
 *
 * @author xuchun
 * @since 2024-08-12
 */
@Service
public class AgencyCertificationAuditServiceImpl extends ServiceImpl<AgencyCertificationAuditMapper, AgencyCertificationAudit> implements IAgencyCertificationAuditService {

    @Resource
    private IAgencyCertificationService agencyCertificationService;
    @Override
    public void submitAudit(AgencyCertificationAuditAddReqDTO dto) {
        dto.setServeProviderId( UserContext.currentUserId() );
        //校验用户是否已经认证通过
        AgencyCertification agencyCertification = agencyCertificationService
                .lambdaQuery()
                .eq(AgencyCertification::getId, dto.getServeProviderId())
                //.eq(WorkerCertification::getCertificationStatus, CertificationStatusEnum.SUCCESS.getStatus())
                .one();
        if (agencyCertification != null && agencyCertification.getCertificationStatus() == CertificationStatusEnum.SUCCESS.getStatus()) {
            throw new ForbiddenOperationException("该机构已经认证通过");
        }
        //校验用户是否已经提交审核
        AgencyCertificationAudit agencyCertificationAudit =
                this.lambdaQuery()
                        .eq(AgencyCertificationAudit::getServeProviderId, dto.getServeProviderId())
                        .eq(AgencyCertificationAudit::getCertificationStatus, CertificationStatusEnum.PROGRESSING.getStatus())
                        .one();
        if (agencyCertificationAudit != null) {
            throw new ForbiddenOperationException("该机构已经提交审核，请勿重复提交");
        }
        agencyCertificationAudit = BeanUtil.copyProperties(dto, AgencyCertificationAudit.class);
        agencyCertificationAudit.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        agencyCertificationAudit.setAuditStatus(CertificationAuditStatusEnum.NOT_AUDIT.getStatus());
        boolean result = this.save(agencyCertificationAudit);
        if (!result) {
            throw new ForbiddenOperationException("提交审核失败");
        }
        agencyCertificationService.removeById( dto.getServeProviderId() );
        agencyCertification = BeanUtil.copyProperties(dto, AgencyCertification.class);
        agencyCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        agencyCertification.setId(dto.getServeProviderId());
        agencyCertificationService.save(agencyCertification);
    }

    @Override
    public Map<String, String> getRejectReason() {
        AgencyCertificationAudit agencyCertificationAudit =
                this.lambdaQuery()
                        .eq(AgencyCertificationAudit::getAuditStatus, CertificationAuditStatusEnum.AUDITED.getStatus())
                        .eq(AgencyCertificationAudit::getCertificationStatus, CertificationStatusEnum.FAIL.getStatus())
                        .eq(AgencyCertificationAudit::getServeProviderId, UserContext.currentUserId())
                        .orderByDesc(AgencyCertificationAudit::getAuditTime)
                        .last(" limit 1")
                        .one();
        if (agencyCertificationAudit != null) {
            return Map.of("rejectReason", agencyCertificationAudit.getRejectReason());
        }
        return null;
    }

    @Override
    public PageResult<AgencyCertificationAuditResDTO> queryPage(AgencyCertificationAuditPageQueryReqDTO pageDTO) {
        Page<AgencyCertificationAudit> page = PageUtils.parsePageQuery(pageDTO, AgencyCertificationAudit.class);
        baseMapper.selectPage(page,
                Wrappers.<AgencyCertificationAudit>lambdaQuery()
                        .eq(pageDTO.getAuditStatus()!=null,AgencyCertificationAudit::getAuditStatus, pageDTO.getAuditStatus())
                        .eq(pageDTO.getCertificationStatus()!=null,AgencyCertificationAudit::getCertificationStatus, pageDTO.getCertificationStatus())
                        .like(StrUtil.isNotEmpty(pageDTO.getName()),AgencyCertificationAudit::getName,pageDTO.getName())
                        .like(StrUtil.isNotEmpty(pageDTO.getLegalPersonName()),AgencyCertificationAudit::getLegalPersonName,pageDTO.getLegalPersonName())
        );
        return PageUtils.toPage(page, AgencyCertificationAuditResDTO.class);
    }

    @Override
    public void audit(Long id, Integer certificationStatus, String rejectReason) {
        AgencyCertificationAudit agencyCertificationAudit = getById(id);
        if (agencyCertificationAudit == null) {
            throw new ForbiddenOperationException("审核信息不存在");
        }
        if (CertificationAuditStatusEnum.AUDITED.getStatus() == agencyCertificationAudit.getAuditStatus()) {
            throw new ForbiddenOperationException("该信息已经审核结束");
        }
        boolean update = this.lambdaUpdate()
                .eq(AgencyCertificationAudit::getId, id)
                .set(AgencyCertificationAudit::getAuditStatus, CertificationAuditStatusEnum.AUDITED.getStatus())
                .set(AgencyCertificationAudit::getCertificationStatus, certificationStatus)
                .set(StrUtil.isNotEmpty(rejectReason), AgencyCertificationAudit::getRejectReason, rejectReason)
                .set(AgencyCertificationAudit::getAuditorId, UserContext.currentUserId())
                .set(AgencyCertificationAudit::getAuditorName, UserContext.currentUser().getName())
                .set(AgencyCertificationAudit::getAuditTime, LocalDateTime.now())
                .update();
        if (!update) {
            throw new ForbiddenOperationException("审核失败");
        }
        //更新认证信息
        boolean result  = agencyCertificationService
                .lambdaUpdate().eq(AgencyCertification::getId, agencyCertificationAudit.getServeProviderId())
                .set(AgencyCertification::getCertificationStatus, certificationStatus)
                .update();
        if (!result){
            throw new ForbiddenOperationException("保存认证信息失败");
        }
    }
}
